package com.gmall.batch.gmallbatch.biz;

import com.gmall.batch.gmallbatch.anno.DataSource;
import com.gmall.batch.gmallbatch.model.User;
import com.gmall.batch.gmallbatch.service.UserService;
import com.gmall.common.enums.DbEnum;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @author HL.Wu
 * @date 2020/7/10 14:09
 * gmall-service
 * for:
 */
@Component
public class UserBiz {

    private final UserService userService;

    private final TransactionTemplate transactionTemplate;

    public UserBiz(UserService userService, TransactionTemplate transactionTemplate) {
        this.userService = userService;
        this.transactionTemplate = transactionTemplate;
    }

    @DataSource(DbEnum.MASTER)
    public int saveBase1() {
        User user = initUser(1);
        return userService.save(user);
    }

    @DataSource(DbEnum.SLAVE)
    public int saveBase2() {
        User user = initUser(2);
        return userService.save(user);
    }

    @DataSource(DbEnum.MASTER)
    public int saveBase1Exception() {
      return transactionTemplate.execute(action ->{
          int i = 0;
            try {
                User user = initUser(11);
                i = userService.save(user);
                throw new Exception("事务异常测试");
            } catch (Exception e) {
                e.printStackTrace();
                action.setRollbackOnly();
                i = 0;
            }
           return i;
       });
    }

    @DataSource(DbEnum.SLAVE)
    public int saveBase2Exception() {
       return transactionTemplate.execute(action ->{
           int i = 0;
            try {
                User user = initUser(12);
                i = userService.save(user);
                throw new Exception("事务异常测试");
            } catch (Exception e) {
                e.printStackTrace();
                action.setRollbackOnly();
                i = 0;
            }
           return i;
        });
    }

    public User initUser(int dataBaseName) {
        User user = new User();
        user.setUserName("mackjie:" + dataBaseName);
        user.setNickName("nick name :" + dataBaseName);
        return user;
    }
}
